/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.view;

import entity.Contact;
import entity.ContactCompany;
import entity.JobAction;
import entity.JobGenerateId;
import entity.JobItems;
import entity.JobPeriod;
import entity.JobStatus;
import entity.JobStatusStatement;
import entity.Jobs;
import entity.Message;
import entity.Users;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.ContactCompanyFacade;
import session.ContactFacade;
import session.JobActionFacade;
import session.JobGenerateIdFacade;
import session.JobItemsFacade;
import session.JobPeriodFacade;
import session.JobStatusFacade;
import session.JobStatusStatementFacade;
import session.JobsFacade;
import session.UsersFacade;

/**
 *
 * @author owtee
 */
public class ApplicationAddPre extends HttpServlet {

    @EJB
    private UsersFacade usersFacade;
    @EJB
    private ContactFacade contactFacade;
    @EJB
    private JobStatusStatementFacade jobStatusStatementFacade;
    @EJB
    private JobsFacade jobsFacade;
    @EJB
    private JobStatusFacade jobStatusFacade;
    @EJB
    private ContactCompanyFacade contactCompanyFacade;
    @EJB
    private JobItemsFacade jobItemsFacade;
    @EJB
    private JobActionFacade jobActionFacade;
    @EJB
    private JobPeriodFacade jobPeriodFacade;
    @EJB
    private JobGenerateIdFacade jobGenerateIdFacade;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            try {
                // Create application ID
                // Get year month day                               
                Calendar calendar = Calendar.getInstance();
                Date date = calendar.getTime();
                SimpleDateFormat sdfAppId = new SimpleDateFormat("yyMMdd", Locale.US);
                String dateSdfAppId = sdfAppId.format(date);

                JobGenerateId jobGenerateIdTmp = jobGenerateIdFacade.find(Integer.parseInt(dateSdfAppId));
                // Check not found start application id
                if (jobGenerateIdTmp == null) {
                    JobGenerateId jobGenId = new JobGenerateId();
                    jobGenId.setJobDate(Integer.parseInt(dateSdfAppId));
                    jobGenId.setJobId(1);
                    jobGenerateIdFacade.create(jobGenId);
                }

                // Get application id
                JobGenerateId jobGenerateId = jobGenerateIdFacade.find(Integer.parseInt(dateSdfAppId));
                String appId = jobGenerateId.getJobDate() + "/" + jobGenerateId.getJobId();

                // Insert next application id
                jobGenerateId.setJobId(jobGenerateId.getJobId() + 1);
                jobGenerateIdFacade.edit(jobGenerateId);
                // End Create application ID

                // Get session
                HttpSession session = request.getSession();
                Users member = (Users) session.getAttribute("member");

                List<JobPeriod> jobPeriodLst = jobPeriodFacade.findByActiveFlag(true);

                List<JobAction> jobActionLst = jobActionFacade.findByActiveFlag(true);

                List<JobItems> jobItemLst = jobItemsFacade.findByActiveFlag(true);

                List<ContactCompany> conComLst = contactCompanyFacade.findByActiveFlag(true);

                // Generate application detail 
                JobStatus jobStatusDef = jobStatusFacade.find("00");
                JobPeriod jobPeriodDef = jobPeriodFacade.find(1);
                Contact conDef = contactFacade.find(1);
                Users userDef = usersFacade.find("1");

                Jobs job = new Jobs();
                job.setJobId(appId);
                job.setRequestUser(member);
                job.setRequestDate(new Date());
                job.setPeriodId(jobPeriodDef);
                job.setConId(conDef);
                job.setMsgUser(userDef);
                job.setStatusId(jobStatusDef);
                job.setActiveFlag(true);
                job.setCreateUser(member.getUserId());
                job.setCreateDate(new Date());
                job.setModifyUser(member.getUserId());
                job.setModifyDate(new Date());
                jobsFacade.create(job);

                JobStatusStatement jobStatusStatement = new JobStatusStatement();
                jobStatusStatement.setJobId(job);
                jobStatusStatement.setStatusId(jobStatusDef);
                jobStatusStatement.setCreateUser(member.getUserId());
                jobStatusStatement.setCreateDate(new Date());
                jobStatusStatement.setModifyUser(member.getUserId());
                jobStatusStatement.setModifyDate(new Date());
                jobStatusStatementFacade.create(jobStatusStatement);

                // Set data to form                
                request.setAttribute("jobPeriodLst", jobPeriodLst);
                request.setAttribute("jobActionLst", jobActionLst);
                request.setAttribute("jobItemLst", jobItemLst);
                request.setAttribute("conComLst", conComLst);
                request.setAttribute("job", job);

            } catch (Exception ex) {
                List<Message> mesLst = new ArrayList<Message>();
                Message message = new Message();
                message.setMesDetail(ex.getMessage());
                mesLst.add(message);
                request.setAttribute("mesLst", mesLst);
            }

            RequestDispatcher rd = request.getRequestDispatcher("application_add.jsp");
            rd.forward(request, response);

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
